<!--
 * @Author: alenjzhang
 * @Date: 2024-04-06 18:32:11
 * @Description: tag 单选
-->
<template>
	<div :class="clsx('single-tag-checked', className)">
		<a-checkable-tag v-for="(item) in tagsData" :key="item.value"
			@change="(check: boolean) => handleChange(check, item.value)" :checked="selectTags[item.value]">
			{{ item.label }}
		</a-checkable-tag>
	</div>
</template>
<script lang="ts" setup>
import { useCustomForm } from '@/hooks';
import type { MutipleType } from '@/types';
import clsx from 'clsx';
import { reactive, watch } from 'vue';

const field = useCustomForm();

interface Props {
	className?: string;
	options: Array<{
		label: string;
		value: MutipleType;
	}>
	value?: Array<string>;
}
const props = defineProps<Props>();

const emit = defineEmits(['update:value']);

const tagsData = reactive(props.options || []);
const selectTags = reactive(props.options.reduce((json: Record<string, any>, curr) => {
	json[curr.value] = false;
	return json;
}, {}));


const handleChange = (check: boolean, key: MutipleType) => {
	if (check && selectTags[key]) return;
	for (const id of Object.keys(selectTags)) {
		if (id === key) {
			selectTags[id] = check;
		} else {
			selectTags[id] = false;
		}
	}
	emit('update:value', [key]);
	field.onFieldChange();
};

watch(() => props.value, (values) => {
	if (values) {
		if (values.length) {
			for (const item of values) {
				selectTags[item] = true;
			}
		} else {
			for (const key of Object.keys(selectTags)) {
				selectTags[key] = false;
			}
		}
	}
}, {
	immediate: true
});

</script>

<style lang="less" scoped>
.single-tag-checked {
	:deep(.ant-tag) {
		padding: 5px 10px;
		border: 1px solid #d9d9d9;
	}
}
</style>
